package com.clp.protocol.iec104.server.pipeline.filter;

import com.clp.protocol.core.utils.AssertUtil;
import io.netty.handler.ipfilter.IpFilterRule;
import io.netty.handler.ipfilter.IpFilterRuleType;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class IpWhiteListFilterRule implements IpFilterRule {
    private final List<String> whileList;

    public IpWhiteListFilterRule(String... whileList) {
        this(Arrays.asList(whileList));
    }

    public IpWhiteListFilterRule(List<String> whileList) {
        AssertUtil.notNull(whileList, "whileList");
        this.whileList = whileList;
    }

    @Override
    public boolean matches(InetSocketAddress remoteAddress) {
        String host = remoteAddress.getHostString();
        boolean isMatch = whileList.contains(host);
        if (!isMatch) {
            log.warn("拒绝连接: {}", host);
        }
        return isMatch;
    }

    @Override
    public IpFilterRuleType ruleType() {
        return IpFilterRuleType.ACCEPT;
    }
}
